//
//  TabBar.swift
//  iPad_QQ
//
//  Created by 李善武 on 16/4/30.
//  Copyright © 2016年 李善武. All rights reserved.
//

import UIKit
@objc protocol TabBarDelegate : NSObjectProtocol{
    optional func tabbarDidClickItem( from : Int ,to : Int)
}
class TabBar: UIView {
    
    private var clickedItem : UIButton?
    
    // 设置icon为未选中
    func unSelected(){
        clickedItem?.selected = false
    }
    // 不要写到方法中，否则访问不到
    var delegate : TabBarDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
         self.setTabBarItems("tab_bar_feed_icon", title: "动态")
         self.setTabBarItems("tab_bar_passive_feed_icon", title: "关心")
         self.setTabBarItems("tab_bar_pic_wall_icon", title: "照片墙")
         self.setTabBarItems("tab_bar_e_album_icon", title: "电子相册")
         self.setTabBarItems("tab_bar_friend_icon", title: "朋友")
         self.setTabBarItems("tab_bar_e_more_icon", title: "更多")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     // 让外界告知屏幕的方向
    func rotateToLandscape(isLandscape : Bool){
        let count = subviews.count
        self.frame.size.width  = (superview?.frame.width)!
        self.frame.size.height =  dockItemHeight * CGFloat(count)
        
        // 设置子控件的frame
        for var i = 0 ; i < count ; i++ {
           let btnItem = subviews[i]
            
           btnItem.frame.size.width = self.frame.width
           btnItem.frame.size.height = dockItemHeight
           btnItem.frame.origin.y = dockItemHeight*CGFloat(i)
            
        }
    }

}

extension  TabBar {
    private func setTabBarItems(imageName : String ,title : String){
        // 创建tabBarItem
        let tabBarItem = TabBarItem()
        tabBarItem.tag = subviews.count
        addSubview(tabBarItem)
        
        // 设置tabBarItem属性
        tabBarItem.setImage(UIImage(named: imageName), forState: .Normal)
        tabBarItem.setBackgroundImage(UIImage(named: "tabbar_separate_selected_bg"), forState: .Selected)
        tabBarItem.setTitle(title, forState: .Normal)
        
        // 设置监听事件
        tabBarItem.addTarget(self, action: "btnSelected:", forControlEvents: .TouchDown)
    }
}

// 设置tabBarItem选中和未选中
extension TabBar{
    
    @objc private func btnSelected(selectedBtn : UIButton){
        // 这种语法的好处
        let tag = clickedItem?.tag ?? 0
        // 调用代理
        delegate?.tabbarDidClickItem!(tag, to: selectedBtn.tag)
        
        clickedItem?.selected = false
        clickedItem = selectedBtn
        clickedItem?.selected = true
    }
}

